package view.customer;

import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import controller.OrderController;
import dao.ProductMsgDao;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.DatePicker;
import pojo.order.OrderEntity;
import pojo.product.ProductMsgEntity;
import view.Main;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author Limohan
 */
public class NewOrderController {

    private Main myApp;
    private static String userId;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    public void setApp(Main myApp) {
        this.myApp = myApp;
    }

    public void setUserId(String userId) {
        NewOrderController.userId = userId;
    }

    public NewOrderController() {
    }

    @FXML
    private JFXTextField amount;

    @FXML
    private JFXTextField cosignee;

    @FXML
    private JFXComboBox<String> productName;

    @FXML
    private JFXTextField address;

    @FXML
    private DatePicker handInTimePicker;

    @FXML
    private DatePicker deadLinePicker;

    @FXML
    private JFXTextField phone;

    @FXML
    void initialize() throws IOException {
        ProductMsgDao productMsgDao = new ProductMsgDao();
        List<ProductMsgEntity> msgJson = productMsgDao.findMsgList();
        if (msgJson != null) {
            for (ProductMsgEntity productMsgEntity : productMsgDao.findMsgList()) {
                productName.getItems().add(productMsgEntity.getName());
            }
        }
    }

    @FXML
    void returnManage(ActionEvent event) throws IOException {
        myApp.goToCustomerOrderPage();
    }

    @FXML
    void saveNewOrder(ActionEvent event) throws IOException {
        OrderEntity order = new OrderEntity();
        OrderController orderController = OrderController.getInstance();
        Date date = new Date();
        order.setCode("PD" + sdf.format(date));
        order.setName(productName.getValue());
        order.setAddress(address.getText());
        order.setAmount(amount.getText());
        order.setConsignee(cosignee.getText());
        order.setHandInDate(handInTimePicker.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        order.setDeahline(deadLinePicker.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        order.setPhone(phone.getText());
        order.setOrderStateForCustomer("已保存");
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("!");
        alert.setContentText(orderController.addMsg(order));
        alert.showAndWait();


    }
}

